<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Model\Access;
use Illuminate\Routing\Router;
use App\Repositories\Access as AccessReposity;
use App\Http\Requests\AccessRequest;
use Illuminate\Validation\ValidationException;

class AccessController extends Controller
{
    public function __construct(AccessReposity $repo)
    {
        parent::__construct($repo);	
    }
	
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function home(Request $request)
    {
		return $this->success(Access::get());
    }
	
    public function uri(Request $request)
    {
        $routes = collect(app('router')->getRoutes())->map(function ($route) {
			if(in_array("permit:api",$route->gatherMiddleware())){
				return [
					'method' => implode('|', $route->methods()),
					'path'    => $route->uri()
				];
			}
        })->whereNotNull()->values()->all();

		return $this->success($this->getRepositories()->uri($routes));
    }
    public function store(AccessRequest $request)
    {
		$access=Access::where("path",$request->path)->where("method",$request->method);
		
		if($request->id){
			$access=$access->where("id","<>",$request->id);
		}
		
		if($access->first()){
			throw ValidationException::withMessages(["path" => "该权限路由已添加过"]);
		}
		
		$this->getRepositories()->store($request->all(),['form'=>['user'=>$request->user]]);
		
		return $this->success("权限保存成功");
	}
	
    public function remove(Request $request)
    {
		$this->getRepositories()->remove($request->all(),['form'=>['user'=>$request->user]]);
		
		return $this->success("删除权限成功");
	}
}
